package ptu.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ptu.dao.ManagerDao;
import ptu.dao.UserDao;
import ptu.entity.Manager;
import ptu.entity.User;
import ptu.result.Result;
import ptu.service.ManagerService;
import ptu.service.UserService;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private ManagerDao managerDao;

    @Override
    public Result selectAll() {
        List<User> list = userDao.selectAll();
        if (list==null&&list.size()<0){
            return Result.error();
        }
        return Result.success(list);
    }

    @Override
    public Result login(String username,String password) {
        User user = userDao.selectByUsername(username);
        if(user==null){
            Manager manager = managerDao.selectByUsername(username);
            if(manager==null){
                return Result.error("用户不存在");
            }else if(!password.equals(manager.getPassword())){
                return Result.error("管理员密码错误");
            }
            manager.setPassword("");
            return Result.success("管理员登录成功",manager);
        }else if(!password.equals(user.getPassword())){
            return Result.error("用户密码错误");
        }
        user.setPassword("");
        return Result.success("用户登录成功",user);
    }

    @Override
    public Result register(User user) {
        User user1 = userDao.selectByUsername(user.getUsername());
        if(user1!=null){
            return Result.error("用户已存在");
        }
        user.setAmount(0);
        int row = userDao.insert(user);
        if(row<1){
            return Result.error();
        }
        return Result.success();
    }

    @Override
    public Result logout(String username) {
        int row = userDao.delete(username);
        if(row<1){
            return Result.error();
        }
        return  Result.success();
    }

    @Override
    public Result update(User user) {
        userDao.update(user);
        return Result.success();
    }

    @Override
    public Result selectByUsername(String username) {
        User user = userDao.selectByUsername(username);
        if(user==null){
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    @Override
    public Result delete(String username) {
        int delete = userDao.delete(username);
        return Result.success();
    }

    @Override
    public User getUserById(Integer id) {
        return userDao.selectById(id);
    }


}
